$(function () {
    window.hotelRoomConstant = {
        'cover': 1,
        'gallery': 2
    };
    var emptyFunction = function () {
        $('#refund-form').removeClass('hidden');
    };
    var tip = function (obj, info) {
        obj.tip({
            content: info,
            background: "#000",
            color: "#fff"
        });
    };

    // 初始化封面信息
    ajaxRequest('/Home/RoomSetting/roomType', {
        hotel: window.currentHotel
    }, 'POST', function (data) {
        var templateRoom = $('#templateRoom');
        var roomHTML = '';
        window.initRoom = data.data;
        $.each(window.initRoom, function (key, value) {
            var template = $(templateRoom.clone().html()).attr('id',value.id).attr('name',value.name);
            template.find('.picture-info-title').html(value.name);
            var templateSwitch = template.find('.switch-input');
            var templateSwitchLabel = template.find('.switch-label');
            if (value.coverImageUrl !== undefined && value.coverImageUrl !== null) {
                template.find('.picture').css('background-image', 'url(' + value.coverImageUrl + ')').css('background-size', '100%').removeClass('hidden');
            }
            if (value.enable !== 0) {
                templateSwitch.attr('checked', true);
                templateSwitchLabel.html(templateSwitchLabel.attr('data-info-open'));
            } else {
                templateSwitchLabel.html(templateSwitchLabel.attr('data-info-close'));
            }
            roomHTML += template.prop('outerHTML');
        });
        $('#roomContainer').html(roomHTML);
        //引导页
        var discountGuidePage = $('.discountGuidePage');
        ajaxRequest('/Home/GuidancePage/getGuidanceData', {
            'guidances':'minus',
        }, 'post', function(data){
            if(data.data.minus){
                discountGuidePage.removeClass('hidden');
            };
        });       
        discountGuidePage.on('click','.roger',function(e){
            ajaxRequest('/Home/GuidancePage/setGuidanceData', {
                'guidances':'minus',
            }, 'post', function(data){
                discountGuidePage.addClass('hidden');
            });        
        });        
        componentHandler.upgradeAllRegistered();
        $('#refund-form').removeClass('hidden');
    }, emptyFunction);
    $('#roomContainer').on('click', '.picuture-upload, .picture-re-upload', function (e) {
        var index = $(this).parents('.picture-with-setting').index();
        $('#submitPicture').data('config', 'bookRoomTypeCover').data('type', window.hotelRoomConstant.cover).data('value', index);
        $('#pictureSelector').trigger('click');
    }).on('click', '.switch', function (e) {
        e.preventDefault();
        var index = $(this).parents('.picture-with-setting').index();
        var checked = $(this).find('.switch-input').prop('checked');
        var label = $(this).find('.switch-label');
        var self = this;

        if (checked) {
            ajaxRequest('/Home/RoomSetting/disableRoomType', {
                hotel: window.currentHotel,
                roomType: window.initRoom[index].id
            }, 'POST', function (data) {
                self.MaterialSwitch.off();
                label.html(label.data('info-close'));
            }, function (error) {
                window.alert(lang('undercarriage'));
            });
        } else {
            ajaxRequest('/Home/RoomSetting/enableRoomType', {
                hotel: window.currentHotel,
                roomType: window.initRoom[index].id
            }, 'POST', function (data) {
                self.MaterialSwitch.on();
                label.html(label.data('info-open'));
            }, function (error) {
                if (error.responseJSON === undefined) {
                    window.alert(lang('grounding'));
                } else if (error.responseJSON.status == 305 || error.responseJSON.status == 411){
                    window.alert(error.responseJSON.info);
                } else {
                    window.alert(lang('grounding'));
                }
            });
        }
    }).on('click', '.setting-price', function (e) {
        e.preventDefault();
        var index = $(this).parents('.picture-with-setting').index();
        $('#settingPriceModal').modal('show');
        $('#requestPrice').val(window.initRoom[index].price);
        $('#submitPrice').data('value', index);
        formInlineRight($('#requestPrice'));
        formInlineRight($('#submitPrice'));
    }).on('click', '.setting-desc', function (e) {
        e.preventDefault();
        var index = $(this).parents('.picture-with-setting').index();
        $('#settingDescModal').modal('show');
        $('#requestDesc').val(window.initRoom[index].description);
        $('#submitDesc').data('value', index);
        formInlineRight($('#requestDesc'));
        formInlineRight($('#submitDesc'));
    }).on('click', '.setting-gallery', function (e) {
        e.preventDefault();
        var index = $(this).parents('.picture-with-setting').index();
        $('#settingGalleryModal').modal('show');
        $('#settingGalleryContainer').data('value', index);
        refreshGallery(window.initRoom[index].picture);
    });

    $('#settingPriceModal').inputValidate({
        submit: {
            query: '#submitPrice'
        },
        inputs: [{
            query: '#requestPrice',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('type.pay01'),
            emptyMessage: lang('type.pay02')
        }]
    });

    $('#submitPrice').on('successSubmit.amos.inputValidate', function (e) {
        var price = $('#requestPrice').val();
        if (parseFloat(price) <= 0 || parseFloat(price) > 999999.99) {
            formInlineTip($('#requestPrice'), lang('type.pay01'));
            return;
        }
        var submitBtn = $(this);
        var index = submitBtn.data('value');
        ajaxRequest('/Home/RoomSetting/saveRoomTypePrice', {
            hotel: window.currentHotel,
            roomType: window.initRoom[index].id,
            price: price,
        }, 'POST', function (data) {
            window.initRoom[index].price = price;
            $('#settingPriceModal').modal('hide');
        }, null, submitBtn);
    });

    $('#settingDescModal').inputValidate({
        submit: {
            query: '#submitDesc'
        },
        inputs: [{
            query: '#requestDesc',
            regexp: /.{0,50}/,
            message: lang('type.desc50'),
            require: false
        }]
    });

    $('#submitDesc').on('successSubmit.amos.inputValidate', function (e) {
        var submitBtn = $(this);
        var index = submitBtn.data('value');
        var desc = $('#requestDesc').val();
        ajaxRequest('/Home/RoomSetting/saveRoomTypeDescription', {
            hotel: window.currentHotel,
            roomType: window.initRoom[index].id,
            description: desc,
        }, 'POST', function (data) {
            window.initRoom[index].description = desc;
            $('#settingDescModal').modal('hide');
        }, null, submitBtn);
    });

    var settingGalleryContainer = $('#settingGalleryContainer');
    settingGalleryContainer.on('click', '.picuture-upload', function (e) {
        $('#submitPicture').data('config', 'bookRoomType').data('type', window.hotelRoomConstant.gallery).removeData('value');
        $('#pictureSelector').trigger('click');
    }).on('click', '.picture-remove', function (e) {
        e.preventDefault();
        e.stopPropagation();
        if (window.confirm(lang('delete'))) {
            var index = settingGalleryContainer.data('value');
            var items = window.galleryItems.slice(0);
            items.splice($(this).parents('.picture-container').index(), 1);
            ajaxRequest('/Home/RoomSetting/saveRoomTypeImage', {
                hotel: window.currentHotel,
                roomType: window.initRoom[index].id,
                url: items.join(','),
            }, 'POST', function (data) {
                refreshGallery(items);
                window.initRoom[index].picture = window.galleryItems;
            }, function (error) {
                if (typeof error.responseJSON == 'undefined') {
                    window.alert(lang('tip.system'));
                } else {
                    window.alert(error.responseJSON.info);
                }
            });

        }
    }).on('click', '.picture-re-upload', function (e) {
        $('#submitPicture').data('config', 'bookRoomType').data('type', window.hotelRoomConstant.gallery).data('value', $(this).parents('.picture-container').index());
        $('#pictureSelector').trigger('click');
    });

    var constructCalendar = function(year,month,data){
        var nowTimestamp = $('#doc').data('time');
        var daysInfos = calendar.getMonthData(year,month,nowTimestamp);
        var html_days = new Array();
        var html_week = '';
        for(var i=0; i<daysInfos.length; i++){
            var cell_type = '';
            var dayInfo = daysInfos[i];

            if(dayInfo.isOverdue){
                cell_type += ' day_overdue';
            }

            var timestamp = dayInfo.timestamp;
            var center_content = window.symbols;
            if(data){
                var price = data['afterDiscount'];
                if(data['price_list'][timestamp]){
                    price = data['price_list'][timestamp]['price'];
                    cell_type += ' price_change';
                }
                center_content += price;
            }

            if(dayInfo.festival){
                cell_type += ' day_festival';
            }

            var right_top = dayInfo.dayNum;
            if(dayInfo.dayNum==1){
                var monthNum = 'month.'+dayInfo.monthNum;
                right_top = lang(monthNum) +'&nbsp;&nbsp;'+right_top;
            }

            var right_bottom = '';
            if(dayInfo.isToday){
                cell_type += ' day_today';
                right_bottom = lang('today');
            }

            var left_bottom = '';
            if(dayInfo.isHoliday){
                cell_type += ' day_holiday';
                left_bottom = lang('type.recess');
            }

            html_week += '<td data-day="'+timestamp+'" data-overdue="'+dayInfo.isOverdue+'" class="' + cell_type + '">';
            html_week += '<span class="center_content">' + center_content + '</span>';
            html_week += '<spna class="left_top">' + dayInfo.festival + '</spna>';
            html_week += '<spna class="right_top">' + right_top + '</spna>';
            html_week += '<spna class="right_bottom">' + right_bottom + '</spna>';
            html_week += '<spna class="left_bottom">' + left_bottom + '</spna>';
            html_week += '</td>';
            if((i+1)%7==0){
                html_days[parseInt(i/7)] = '<tr>'+html_week+'</tr>';
                html_week = '';
            }
        }
        $('#calendar_days').html(html_days.join());
        $('#price_calendar .price_calendar_title').html($('#calendar_months').data('roomTypeName') + ' -'+lang('type.calendar'));
        var discountHtml = lang('default.Pay')+':'+window.symbols+'<span class="roomTypeDefaultPrice">' + data['price'] + '</span>&nbsp&nbsp'+lang('default.discount')+'<input type="text" id="discount_calendar_input" value=' + data['discount'] + '>&nbsp'+lang('default.discount01')+'&nbsp&nbsp'+lang('default.selling')+window.symbols+'<span class="roomPrice">' + data['afterDiscount'] + '</span>&nbsp&nbsp<button type="submit" class="btn-primary btn-sm btn-raised" id="discount_calendar_submit">'+lang('date.ensure')+'</button>';
        $('#price_calendar .discount_calendar_title').html(discountHtml);
        $('#discount_calendar_input').blur(function(){
            var discountValue = $('#discount_calendar_input').val();
            if(!/^\d+(?:\.\d{1,2})?$/.test(discountValue) || parseFloat(discountValue) >10 || parseFloat(discountValue) < 0){
                alert(lang('default.discountVal'));
            } else {
                var discountPrice = data['price'];
                $('.roomPrice').html((discountPrice*(discountValue/10)).toFixed(2));
            }
        });
        //立减
        var discountsWayConatiner = $('.discountsWayConatiner');
        var discountsWayAlreadyConatiner = $('.discountsWayAlreadyConatiner');    
        var minusdiscount = data.minusdiscount;
        if(data.minustype == 0){
            discountsWayAlreadyConatiner.addClass('hidden');
            discountsWayConatiner.removeClass('hidden');
        }else{
            if(data.minustype == 2){
                minusdiscount = parseFloat(minusdiscount)+'%';
            }else{
                minusdiscount = window.symbols+minusdiscount;
            }            
            discountsWayAlreadyConatiner.find('.discounts').text(minusdiscount);
            discountsWayConatiner.addClass('hidden');
            discountsWayAlreadyConatiner.removeClass('hidden');
        };
    };

    //设置折扣值
    $('#price_calendar').on('click','#discount_calendar_submit', function(e) {
        var discountValue = $('#discount_calendar_input').val();
        if(!/^\d+(?:\.\d{1,2})?$/.test(discountValue) || parseFloat(discountValue) >10 || parseFloat(discountValue) < 0){
            alert(lang('default.discountVal'));
        } else {
            var param = {};
            var roomTypeId = window.hotelCurrentRoomTypeId;
            var roomTypeName = window.hotelCurrentRoomTypeName;
            param.hotel = window.currentHotel;
            param.roomtype_id = roomTypeId;
            param.discount = discountValue;

            //显示月份
            var month = calendar.getMonthArray();
            var html_month = "";
            for(var i=0; i<month.length; i++){
                var style = i==0?' class="selected"':'';
                html_month += '<tr' + style + '><td data-year="'+ month[i].year +'" data-month="'+ month[i].month +'"><span>' + month[i].year + lang('calendar.years') + month[i].month + lang('calendar.months')+'</span></td></tr>';
            }
            $('#calendar_months').html(html_month).data('roomTypeId',roomTypeId).data('roomTypeName',roomTypeName);
            //显示日历框
            $('#price_calendar').modal('show');

            ajaxRequest('/Home/RoomSetting/setDiscount', param, 'post', function(result){
                $('#price_calendar .err_info').html('');
                constructCalendar(month[0].year, month[0].month, result.data);
            }, function(error) {
                $('#price_calendar .err_info').html(error.responseJSON.info);
            });
        }
    });
    //显示价格日历
    var showCalendar = function(roomTypeId,year,month){
        var param = {};
        param.hotel = window.currentHotel;
        param.roomtype_id = roomTypeId;
        ajaxRequest('/Home/RoomSetting/getPriceList', param, 'post', function(result){
            constructCalendar(year, month, result.data);
        }, function(error) {
            constructCalendar(year, month, null);
            $('#price_calendar .err_info').html(lang('tip.server'));
        });
    }
    //显示预设价格
    $('#roomContainer').on('click','.priceCalendar', function(e) {
        var roomTypeId = $(this).parents('.picture-with-setting').attr('id');
        var roomTypeName = $(this).parents('.picture-with-setting').attr('name');
        window.hotelCurrentRoomTypeId = roomTypeId;
        window.hotelCurrentRoomTypeName = roomTypeName;

        //显示月份
        var month = calendar.getMonthArray();
        var html_month = "";
        for(var i=0; i<month.length; i++){
            var style = i==0?' class="selected"':'';
            html_month += '<tr' + style + '><td data-year="'+ month[i].year +'" data-month="'+ month[i].month +'"><span>' + month[i].year + lang('calendar.years') + month[i].month + lang('calendar.months')+'</span></td></tr>';
        }
        $('#calendar_months').html(html_month).data('roomTypeId',roomTypeId).data('roomTypeName',roomTypeName);
        //显示日历框
        $('#price_calendar').modal('show');
        //请求价格数据并显示
        showCalendar(roomTypeId, month[0].year, month[0].month);
    });
    //切换月份
    $('#calendar_months').on('click','td',function(){
        $(this).parent().addClass('selected').siblings().removeClass('selected');
        var roomTypeId = $('#calendar_months').data('roomTypeId');
        var year = $(this).data('year');
        var month = $(this).data('month');
        showCalendar(roomTypeId, year, month);
    });
    //设置价格输入框
    $('#calendar_days').on('click','td',function(){
        if($(this).data('overdue')){
            return;
        }
        $(this).addClass('selected');
        $('#price_input').val('').data('price_date', $(this).data('day'));
        $('#set_price_info').html('');
        $('#price_calendar_set').modal('show');
    });
    //输入框焦点
    $('#price_calendar_set').on('shown.bs.modal', function (e) {
        $('#price_input').focus();
    });
    //关闭事件
    $('#price_calendar_set').on('hide.bs.modal', function (e) {
        $('#calendar_days').find('td').removeClass('selected');
    });
    //设置价格
    $('#set_price').on('click',function(){
        var param = {};
        param.hotel = window.currentHotel;
        param.roomtype_id = $('#calendar_months').data('roomTypeId');
        param.price_date = $('#price_input').data('price_date');
        param.price = $('#price_input').val();
        if(!/^\d{1,6}(?:\.\d{1,2})?$/.test(param.price)){
            $('#set_price_info').html(lang('default.payVal'));
            $('#price_input').focus();
            return;
        }
        ajaxRequest('/Home/RoomSetting/setPrice', param, 'post', function(data){
            $('#set_price_info').html('');
            $('#price_calendar_set').modal('hide');
            var roomTypeId = $('#calendar_months').data('roomTypeId');
            var year = $('#calendar_months .selected td').data('year');
            var month = $('#calendar_months .selected  td').data('month');
            showCalendar(roomTypeId, year, month);
        }, function(error) {
            //$('#set_price_info').html(lang('tip.server'));
            $('#set_price_info').html(error.responseJSON.info);
        });
    });

    // 初始化退订规则
    var ImmediatelySwitch = $('#ImmediatelySwitch');
    var bookRoomSwitch = $('#bookRoomSwitch');
    bookRoomSwitch.attr('disabled', true);
    ImmediatelySwitch.attr('disabled', true);
    ajaxRequest('/Home/Hotel/getPayDetail', {
        'hotel': window.currentHotel
    }, 'post', function (data) {
        var hotelInfo = data.data;
        $('#requestRefundDesc').val(hotelInfo.refundrule);
        $('#requestDeposit').val(hotelInfo.deposit);
        if (hotelInfo.minusEnable == 1) {
            ImmediatelySwitch.find('.switch-input').attr("checked",true);
            ImmediatelySwitch.addClass('is-checked');
        }else{
            ImmediatelySwitch.find('.switch-input').removeAttr("checked");
            ImmediatelySwitch.removeClass('is-checked');
        }
        if (hotelInfo.bookMode == 0) {
            bookRoomSwitch.find('.switch-input').attr("checked",true);
            bookRoomSwitch.addClass('is-checked');
        }else{
            bookRoomSwitch.find('.switch-input').removeAttr("checked");
            bookRoomSwitch.removeClass('is-checked');
        }
        bookRoomSwitch.removeAttr('disabled');
        ImmediatelySwitch.removeAttr('disabled');
    }, function (error) {});

    $('#refund-form').inputValidate({
        submit: {
            query: '#submitRefundDesc'
        },
        inputs: [{
            query: '#requestRefundDesc',
            regexp: /.{1,255}/,
            message: lang('default.unsubscribe'),
            emptyMessage: lang('default.unsubscribeNull')
        }, {
            query: '#requestDeposit',
            regexp: window.commonRegexp.roomTypePrice,
            message: lang('default.cash'),
            emptyMessage: lang('default.cashNull')
        }]
    });
    $('#submitRefundDesc').on('successSubmit.amos.inputValidate', function (e) {
        var submitBtn = $(this);
        var params = {};
        params.hotel = window.currentHotel;
        params.rule = $('#requestRefundDesc').val();
        params.deposit = $('#requestDeposit').val();
        ajaxRequest('/Home/Hotel/saveRefundRule', params, 'post', function (data) {
            formInlineTip(submitBtn, lang('successfullySave'), 2);
        }, null, submitBtn);
    });

    // 房态开关
    $('#bookRoomSwitch').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        
        var checkbox = $(this).find('input[type=checkbox]');
        var isSwitchOn = checkbox.prop('checked');
        var params = {
                hotel: window.currentHotel,
                bookMode: isSwitchOn ? 1 : 0,
            };
        
        ajaxRequest('/Home/RoomSetting/toggleBookMode', params, 'post', function (data, submitBtn) {
            var domBtn = submitBtn[0];
            if (isSwitchOn) {
                domBtn.MaterialSwitch.off();
            } else {
                domBtn.MaterialSwitch.on();
            }
            tip(submitBtn, lang('successfullySet'));
        }, function (error, submitBtn, defaultErrorHandler) {
            if (error.responseJSON === undefined) {
                tip(submitBtn,lang('tip.system'));
            } else {
                tip(submitBtn, error.responseJSON.info);
            }
        }, me);
    });
    
    //立减开关
    $('#ImmediatelySwitch').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        var checkbox = $(this).find('input[type=checkbox]');
        var isSwitchOn = checkbox.prop('checked');
        var params = {
                hotel: window.currentHotel,
                minusEnable: isSwitchOn ? 0 : 1,
        };
        ajaxRequest('/Home/RoomSetting/toggleMinusEnable', params, 'post', function (data, submitBtn) {
            var domBtn = submitBtn[0];
            if (isSwitchOn) {
                domBtn.MaterialSwitch.off();
            } else {
                domBtn.MaterialSwitch.on();
            }
            tip(submitBtn, lang('successfullySet'));
        }, function (error, submitBtn, defaultErrorHandler) {
            if (error.responseJSON === undefined) {
                tip(submitBtn,lang('tip.system'));
            } else {
                tip(submitBtn, error.responseJSON.info);
            }
        }, me);
    });    
    var requestProportionWayValue = $('#requestProportionWayValue');
    var requestSpecificWayValue = $('#requestSpecificWayValue');
    $("[name='requestWay']").on('click', function(e){
        var value = $(this).data('value');
        if(value == 1){
            requestSpecificWayValue.addClass('hidden');
            requestProportionWayValue.removeClass('hidden');
        }else{
            requestProportionWayValue.addClass('hidden');
            requestSpecificWayValue.removeClass('hidden');
        }
    });
    var discountsWayConatiner = $('.discountsWayConatiner');
    var discountsWayAlreadyConatiner = $('.discountsWayAlreadyConatiner');
    $('#radioWaySubmit').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        var value = 0;
        var whichWay  = $('#requestProportionWay').prop('checked') ? 2 : 1;
        if(whichWay == 2){
            value = $('#requestProportionWayValue').val();
        }else{
            value = $('#requestSpecificWayValue').val();
        }
        if(value == ''){
            value = 0;
        }
        var params = {
                hotel: window.currentHotel,
                minustype: whichWay,
                roomTypeId :$('#calendar_months').data('roomTypeId'),
                minusdiscount : value,
        };        
        ajaxRequest('/Home/RoomSetting/setBookRoomTypeDiscound', params, 'post', function (data, submitBtn) {
            var minusdiscount = data.data.minusdiscount;
            if(whichWay == 2){
                minusdiscount = minusdiscount+'%';
            }else{
                minusdiscount = window.symbols+ parseFloat(minusdiscount).toFixed(2);
            }
            if(value == 0){
                discountsWayAlreadyConatiner.addClass('hidden');
                discountsWayConatiner.removeClass('hidden');
            }else{
                discountsWayAlreadyConatiner.find('.discounts').text(minusdiscount);
                discountsWayConatiner.addClass('hidden');
                discountsWayAlreadyConatiner.removeClass('hidden');
            }
        }, function (error, submitBtn, defaultErrorHandler) {
            if (error.responseJSON === undefined) {
                tip(submitBtn,lang('tip.system'));
            } else {
                tip(submitBtn, error.responseJSON.info);
            }
        }, me);
    });
    $('#radioWayEditSubmit').on('click',function(e){
        discountsWayAlreadyConatiner.addClass('hidden');
        discountsWayConatiner.removeClass('hidden');
    });
    
    //多元货币初始化
    var getHotelCurrency = function(){
        ajaxRequest('/Home/Hotel/getHotelCurrency', {
            "hotel": window.currentHotel,
        }, 'POST', function (data) {
            var currencyHTML = '';
            $.each(data.data, function(index, item) {
                var templateCurrency = $($('#templateaCurrency').clone().html());
                templateCurrency.find('.currency').text(item.name);
                if(item.type == 0){
                    templateCurrency.attr('data-value',item.hotelCurrencyId);
                    templateCurrency.find('.deleteBtn').removeClass('hidden');
                }
                currencyHTML += templateCurrency.prop('outerHTML');
            });
            $('#multiCurrencyContainer').html(currencyHTML);        
        }, function (error) {
            modalAlert(error.responseJSON.info);   
        });          
    }
    getHotelCurrency();
    
    $('.addMultiCurrency').on('click',function(e){
        e.stopPropagation();
        $('#multiCurrencyModal').removeClass('hidden');
    });
    $('#multiCurrencyModal').on('click', '.dropdown-menu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var toggle = liItem.parents('.dropdown-menu').siblings('[data-toggle="dropdown"]');
        liItem.addClass('active');
        liItem.siblings().removeClass('active');
        var value = liItem.data('value');
        var name = item.text();
        toggle.data('value', value);
        toggle.find('.info').html(name);       
    });      
    $('#multiCurrencyModal').on('click','.close',function(e){
        e.stopPropagation();
        $('#multiCurrencyModal').addClass('hidden');
    });
    $('#confirmCurrencyInfo').on('click',function(e){
        e.stopPropagation();
        var submitBtn = $(this);
        var currencyId = $('#multiCurrencyModal').find('[data-toggle="dropdown"]').data('value');
        ajaxRequest('/Home/Hotel/setHotelCurrency', {
            "hotel": window.currentHotel,
            "currencyId":currencyId
        }, 'POST', function (data) {
            getHotelCurrency();
            $('#multiCurrencyModal').addClass('hidden');
            formInlineTip(submitBtn, lang('successfullySave'),2);
        }, function (error) {
            if (error.responseJSON === undefined) {
                formInlineTip(submitBtn, lang('tip.server'));
            } else {
                formInlineTip(submitBtn, error.responseJSON.info);
            }
        });         
    }); 
    // 删除货币
    $('#multiCurrencyContainer').on('click','.deleteBtn',function (e) {
        hotelCurrencyId = $(this).parents('.tag-item').data('value');
    });
    $('#submitCurrencyDelete').on('click', function (e) {
        var param = {
                hotel: window.currentHotel,
                hotelCurrencyId: hotelCurrencyId
            },
            $me = $(this);
        ajaxRequest('/Home/Hotel/deleteHotelCurrency', param, 'post', function(data){
            getHotelCurrency();
            $('#multiCurrencyDeleteModal').modal('hide');
        }, null, $me);
    });   
});
var refreshGallery = function (gallery) {
    window.galleryItems = gallery;
    var templatePicture = $('#templatePicture');
    var galleryHTML = '';
    $.each(gallery, function (key, value) {
        var template = $(templatePicture.clone().html());
        template.find('.picture').removeClass('hidden').css('background-image', 'url(' + value + ')').css('background-size', '100%');
        galleryHTML += template.prop('outerHTML');
    });
    if (gallery.length < 4) {
        galleryHTML += templatePicture.clone().html();
    }
    $('#settingGalleryContainer').html(galleryHTML);
};
/* exported pictureCropperSuccess */
var pictureCropperSuccess = function (imageUrl, imageType) {
    var submitPicture = $('#submitPicture');
    var index = submitPicture.data('value');
    switch (imageType) {
        case window.hotelRoomConstant.cover:
            var roomType = window.initRoom[index].id;
            ajaxRequest('/Home/RoomSetting/saveRoomTypeCover', {
                hotel: window.currentHotel,
                roomType: roomType,
                url: imageUrl
            }, 'POST', function (data) {
                window.initRoom[index].coverImageUrl = imageUrl;
                var childIndex = index + 1;
                var cover = $('#roomContainer').find('.picture-with-setting:nth-child(' + childIndex + ')').find('.picture');
                cover.css('background-image', 'url(' + imageUrl + ')').removeClass('hidden');
                $('#pictureModal').modal('hide');
            }, null, submitPicture);
            break;
        case window.hotelRoomConstant.gallery:
            var items = window.galleryItems.slice(0);
            var roomTypeIndex = $('#settingGalleryContainer').data('value');
            if (index !== undefined) {
                items.splice(index, 1, imageUrl);
            } else {
                items.push(imageUrl);
            }
            ajaxRequest('/Home/RoomSetting/saveRoomTypeImage', {
                hotel: window.currentHotel,
                roomType: window.initRoom[roomTypeIndex].id,
                url: items.join(',')
            }, 'POST', function (data) {
                refreshGallery(items);
                window.initRoom[roomTypeIndex].picture = window.galleryItems;
                $('#pictureModal').modal('hide');
            }, null, submitPicture);
            break;
        default:
            break;
    }
};
